﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvCamCtrl.NET;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using MainFrame;
using System.Threading.Tasks;
using System.Diagnostics;

namespace CameraAcq
{
    public class HikVision: AreaCameraBase
    {
        public bool isInitSuccess = false;//初始化是否完成
        private string findSerialNo;//要查找的序列号
        private MyCamera.MV_CC_DEVICE_INFO interDevice;//相机操作device
        private MyCamera interMycam=new MyCamera();//相当于相机操作句柄
        public MyCamera.MV_CC_DEVICE_INFO_LIST m_pDeviceList;//相机信息列表
        private int _selectedCameraIndex = -1;
        Dictionary<MyCamera.MV_CC_DEVICE_INFO,CamInfo> deviceAndInfo=new Dictionary<MyCamera.MV_CC_DEVICE_INFO, CamInfo>();//相机ID与内部device对应信息
        public List<CamInfo> cameraList = new List<CamInfo>();//找到的相机列表
        List<MyCamera> hikCameraList = new List<MyCamera>();
        MyCamera.cbOutputExdelegate ImageCallback;

        Stopwatch softSW = new Stopwatch();
        //public List<byte[]> imageByteList = new List<byte[]>();//相机输出的byte[]格式的图像列表
        public HikVision(DeviceType dt) : base(dt)
        {

        }
        public HikVision(string camSerial) : base(camSerial)
        {
            findSerialNo = camSerial;
            isInitSuccess= InitCam();
        }
        public int m_selectedCameraIndex
        {
            get { return _selectedCameraIndex; }
            set { _selectedCameraIndex = value; }
        }

        /// <summary>
        /// 初始化相机
        /// </summary>
        /// <returns>初始化成功返回true，否则返回false</returns>
        public bool InitCam()
        {
            try
            {
                if (m_bConnected)
                {
                    displalyInfo.displayInfoMain("此相机已经初始化完成，不需要再初始化");
                    return false;
                }
                displalyInfo.displayInfoMain(findSerialNo+" 相机开始初始化...");
                //IntPtr m= interMycam.GetCameraHandle();
                AcqDeviceList(ref cameraList);
                // ch:获取选择的设备信息 | en:Get selected device information
                interDevice = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[0],
                                                                typeof(MyCamera.MV_CC_DEVICE_INFO));
                bool isfind = false;
                isfind= findDevice(ref interDevice);
                // ch:打开设备 | en:Open device
                if (null == interMycam)
                {
                    interMycam = new MyCamera();
                    if (null == interMycam)
                    {
                        return false;
                    }
                }
                if (!isfind)
                {
                    return false;
                }
                ConnectDev();
                displalyInfo.displayInfoMain(findSerialNo+" 相机初始化成功");
                
                return true;
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(findSerialNo+ "相机初始化失败：" + ex.Message);
                displalyInfo.displayInfoMain(findSerialNo + "相机初始化失败：" + ex.Message);
                return false;
            }
            
        }
        /// <summary>
        /// 根据序列号查找device
        /// </summary>
        /// <param name="devices">根据序列化查找到的device</param>
        /// <returns>如果查到返回true,否则返回false</returns>
        private bool findDevice(ref MyCamera.MV_CC_DEVICE_INFO devices)
        {
            try
            {
                if (findSerialNo == "")
                {
                    //MessageBox.Show("没有找到相对应的相机，请检查");
                    displalyInfo.displayInfoMain("没有找到相对应的相机，请检查");
                    return false;
                }
                //var Findeddevice = deviceAndInfo.Where(v=>v.Value.m_SerialNO==findSerialNo).Select(v=>v.Key);
                devices = deviceAndInfo.FirstOrDefault(v=>v.Value.m_SerialNO==findSerialNo).Key;
                return true;
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show("查找相机出错"+ex.Message);
                displalyInfo.displayInfoMain("查找相机出错" + ex.Message);
                return false;
            }
            
        }
        /// <summary>
        /// 获取同品牌的相机列表
        /// </summary>
        /// <param name="cameralist">输出的相机列表</param>
        public override void AcqDeviceList(ref List<CamInfo> cameralist)
        {
            int nRet;
            // ch:创建设备列表 en:Create Device List
            System.GC.Collect();
            cameralist=new List<CamInfo>();
            nRet = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref m_pDeviceList);
            if (0 != nRet)
            {
                //ShowErrorMsg("Enumerate devices fail!", 0);
                cameralist.Clear();
                return;
            }

            // ch:将设备名添加到列表中 | en:add device name to the list
            for (int i = 0; i < m_pDeviceList.nDeviceNum; i++)
            {
                CamInfo camInfoStruct=new CamInfo();
                MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
                MyCamera.MV_IMAGE_BASIC_INFO ImageInfo = (MyCamera.MV_IMAGE_BASIC_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_IMAGE_BASIC_INFO));
                //MyCamera.MV_FRAME_OUT_INFO_EX ImageInfo1 = (MyCamera.MV_FRAME_OUT_INFO_EX)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_FRAME_OUT_INFO_EX));
                //MyCamera.MV_SAVE_IMAGE_PARAM_EX ImageInfo2 = (MyCamera.MV_SAVE_IMAGE_PARAM_EX)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_SAVE_IMAGE_PARAM_EX));

                if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
                    MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));
                    
                    camInfoStruct.m_Manufacturer = gigeInfo.chManufacturerName;
                    camInfoStruct.m_SerialNO = gigeInfo.chSerialNumber;
                    camInfoStruct.m_UserDefineName = gigeInfo.chUserDefinedName;
                    camInfoStruct.m_CamName = gigeInfo.chModelName;
                                   
                }
                else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
                    MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_USB3_DEVICE_INFO));
                    camInfoStruct.m_Manufacturer = usbInfo.chManufacturerName;
                    camInfoStruct.m_SerialNO = usbInfo.chSerialNumber;
                    camInfoStruct.m_UserDefineName = usbInfo.chUserDefinedName;
                    camInfoStruct.m_CamName = usbInfo.chModelName;
                }
                //camInfoStruct.m_PixDepth =FrameInfo.enPixelType;
                //camInfoStruct.m_ImageHeight =ImageInfo.nHeightMax;
                //camInfoStruct.m_ImageWidth = ImageInfo.nWidthMax;
                
                cameralist.Add(camInfoStruct);
                deviceAndInfo.Add(device,camInfoStruct);
            }
        }

        public override void AcqDeviceList()
        {
            int nRet;
            // ch:创建设备列表 en:Create Device List
            System.GC.Collect();
            nRet = MyCamera.MV_CC_EnumDevices_NET(MyCamera.MV_GIGE_DEVICE | MyCamera.MV_USB_DEVICE, ref m_pDeviceList);
            if (0 != nRet)
            {
                //ShowErrorMsg("Enumerate devices fail!", 0);
                return;
            }

            // ch:将设备名添加到列表中 | en:add device name to the list
            for (int i = 0; i < m_pDeviceList.nDeviceNum; i++)
            {
                MyCamera.MV_CC_DEVICE_INFO device = (MyCamera.MV_CC_DEVICE_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_CC_DEVICE_INFO));
                MyCamera.MV_IMAGE_BASIC_INFO ImageInfo = (MyCamera.MV_IMAGE_BASIC_INFO)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_IMAGE_BASIC_INFO));
                //MyCamera.MV_FRAME_OUT_INFO_EX ImageInfo1 = (MyCamera.MV_FRAME_OUT_INFO_EX)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_FRAME_OUT_INFO_EX));
                //MyCamera.MV_SAVE_IMAGE_PARAM_EX ImageInfo2 = (MyCamera.MV_SAVE_IMAGE_PARAM_EX)Marshal.PtrToStructure(m_pDeviceList.pDeviceInfo[i], typeof(MyCamera.MV_SAVE_IMAGE_PARAM_EX));

                if (device.nTLayerType == MyCamera.MV_GIGE_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stGigEInfo, 0);
                    MyCamera.MV_GIGE_DEVICE_INFO gigeInfo = (MyCamera.MV_GIGE_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_GIGE_DEVICE_INFO));

                    m_manufacturerName = gigeInfo.chManufacturerName;
                    m_SerialNo = gigeInfo.chSerialNumber;
                    m_UserDefineName = gigeInfo.chUserDefinedName;
                }
                else if (device.nTLayerType == MyCamera.MV_USB_DEVICE)
                {
                    IntPtr buffer = Marshal.UnsafeAddrOfPinnedArrayElement(device.SpecialInfo.stUsb3VInfo, 0);
                    MyCamera.MV_USB3_DEVICE_INFO usbInfo = (MyCamera.MV_USB3_DEVICE_INFO)Marshal.PtrToStructure(buffer, typeof(MyCamera.MV_USB3_DEVICE_INFO));
                    m_manufacturerName = usbInfo.chManufacturerName;
                    m_SerialNo = usbInfo.chSerialNumber;
                    m_UserDefineName = usbInfo.chUserDefinedName;
                }
                //camInfoStruct.m_PixDepth =FrameInfo.enPixelType;
                //camInfoStruct.m_ImageHeight =ImageInfo.nHeightMax;
                //camInfoStruct.m_ImageWidth = ImageInfo.nWidthMax;
            }
        }

        private Boolean IsMonoData(MyCamera.MvGvspPixelType enGvspPixelType)
        {
            switch (enGvspPixelType)
            {
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_Mono12_Packed:
                    return true;

                default:
                    return false;
            }
        }

        /************************************************************************
         *  @fn     IsColorData()
         *  @brief  判断是否是彩色数据
         *  @param  enGvspPixelType         [IN]           像素格式
         *  @return 成功，返回0；错误，返回-1 
         ************************************************************************/
        private Boolean IsColorData(MyCamera.MvGvspPixelType enGvspPixelType)
        {
            switch (enGvspPixelType)
            {
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG8:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG10_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGR12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerRG12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerGB12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_BayerBG12_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_RGB8_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YUV422_YUYV_Packed:
                case MyCamera.MvGvspPixelType.PixelType_Gvsp_YCBCR411_8_CBYYCRYY:
                    return true;

                default:
                    return false;
            }
        }

        /// <summary>
        /// 连接并打开相机，采集方式为连续采集
        /// </summary>
        public override bool ConnectDev()
        {
            if (m_bConnected)
            {
                displalyInfo.displayInfoMain("相机设备已打开（连接），不需要再打开");
                return false;
            }
            if (m_pDeviceList.nDeviceNum == 0)
            {               
                //MessageBox.Show("没有发现相机，请检查");
                displalyInfo.displayInfoMain("没有发现相机，请检查");
                return false;
            }
            int nRet = -1;
            
            nRet = interMycam.MV_CC_CreateDevice_NET(ref interDevice);
            if (MyCamera.MV_OK != nRet||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机打开出错");
                displalyInfo.displayInfoMain(findSerialNo + " 相机打开出错：CreateDevice error or getCameraHandle=0");
                return false;
            }
            nRet = interMycam.MV_CC_OpenDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                interMycam.MV_CC_DestroyDevice_NET();
                //MessageBox.Show(findSerialNo+" 相机打开出错");
                displalyInfo.displayInfoMain(findSerialNo+" 相机打开出错：OpenDevice error");
                return false;
            }

            // ch:设置采集连续模式 | en:Set Continues Aquisition Mode
            interMycam.MV_CC_SetEnumValue_NET("AcquisitionMode", 2);// ch:工作在连续模式 | en:Acquisition On Continuous Mode
            interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 0);    // ch:连续模式 | en:Continuous

            
            // ch:注册回调函数 | en:Register image callback
            ImageCallback = new MyCamera.cbOutputExdelegate(GrabImage);

            nRet = interMycam.MV_CC_RegisterImageCallBackEx_NET(ImageCallback, IntPtr.Zero);
            if (MyCamera.MV_OK != nRet)
            {
                //MessageBox.Show("Register Image CallBack Fail");
            }
            //bnGetParam_Click(null, null);// ch:获取参数 | en:Get parameters
            hikCameraList.Add(interMycam);
            //interMycam.MV_CC_StartGrabbing_NET();//开始采集
            ////base.ConnectDev();//调用基类已经被其它调用者重写的对应方法
            //displalyInfo.displayInfoMain(findSerialNo+" 相机打开成功");
            m_bConnected = true;
            displalyInfo.displayInfoMain("相机已连接");
            return true;
        }

        public override bool StartGrab()
        {
            if (m_bGrabbed)
            {
                displalyInfo.displayInfoMain("已开始采集");
                return false;
            }
            int nRet;
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return false;
            }
            nRet= interMycam.MV_CC_StartGrabbing_NET();
            if (MyCamera.MV_OK==nRet)
            {
                m_bGrabbed = true;
                displalyInfo.displayInfoMain("开始采集");
                return true;
            }
            else
            {
                //MessageBox.Show(findSerialNo+" 采集图像出错");
                displalyInfo.displayInfoMain(findSerialNo+" 采集图像出错");
                return false;
            }
            //base.StartGrab();
        }

        public override bool stopGrab()
        {
            if (!m_bGrabbed)
            {
                displalyInfo.displayInfoMain("采集未开始，不用停止");
                return false;
            }
            int nRet;
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return false;
            }
            nRet = interMycam.MV_CC_StopGrabbing_NET();
            if (MyCamera.MV_OK == nRet)
            {
                displalyInfo.displayInfoMain("采集已停止");
                m_bGrabbed = false;
                return true;
            }
            else
            {
                //MessageBox.Show(findSerialNo+" 相机停止采集失败");
                displalyInfo.displayInfoMain(findSerialNo+" 相机停止采集失败");
                return false;
            }
            //return base.stopGrab();
        }
        private void GrabImage(IntPtr pData, ref MyCamera.MV_FRAME_OUT_INFO_EX pFrameInfo, IntPtr pUser)
        {
           try
           {
                //displalyInfo.displayInfoMain("进入采集回调.耗时：" + softSW.ElapsedMilliseconds.ToString());
                if (pData != null)
                {
                    //IntPtr pBufForSaveImage = IntPtr.Zero;
                    //pBufForSaveImage = Marshal.AllocHGlobal((int)(pFrameInfo.nWidth * pFrameInfo.nHeight));

                    uint nWidth = pFrameInfo.nWidth;
                    m_ImgWidth =(int) nWidth;

                    uint nHeight = pFrameInfo.nHeight;
                    m_ImgHeight = (int)nHeight;

                    byte[] imageByte = new byte[nWidth * nHeight];

                    Marshal.Copy(pData, imageByte, 0, (int)nWidth * (int)nHeight);
                    //Marshal.Copy(pData, imageByte, 0, (int)nWidth * (int)nHeight);
                    m_imageByteList.Add(imageByte);
                    if (m_imageByteList.Count>5)
                    {
                        m_imageByteList.RemoveAt(0);
                    }
                    m_imageNumber++;
                    Task.Factory.StartNew(()=> imageOut(m_imageByteList)) ;//异步委托输出
                    
                    //displalyInfo.displayInfoMain("图像输出完成.耗时："+ softSW.ElapsedMilliseconds.ToString());
                }
            }
           catch (System.Exception ex)
            {
                //MessageBox.Show(findSerialNo+" 相机输出图像数据出错：" + ex.Message);
                displalyInfo.displayInfoMain(findSerialNo+" 相机输出图像数据出错：" + ex.Message);
            }
            finally
            {
                GC.Collect();
            }
        }

        /// <summary>
        /// 关闭相机
        /// </summary>
        public override bool DisConnectDev()
        {
            if (!m_bConnected)
            {
                displalyInfo.displayInfoMain("相机未打开（连接），不需要关闭（断开）");
                return false;
            }
            // ch:关闭设备 | en:Close Device
            int nRet;
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return false;
            }
            interMycam.MV_CC_StopGrabbing_NET();
            nRet = interMycam.MV_CC_CloseDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                //MessageBox.Show(findSerialNo+" 相机CloseDevice出错");
                displalyInfo.displayInfoMain(findSerialNo+" 相机CloseDevice出错");
                return false;
            }

            nRet = interMycam.MV_CC_DestroyDevice_NET();
            if (MyCamera.MV_OK != nRet)
            {
                //MessageBox.Show(findSerialNo+" 相机DestroyDevice出错");
                displalyInfo.displayInfoMain(findSerialNo+" 相机DestroyDevice出错");
                return false;
            }
            m_bConnected = false;
            displalyInfo.displayInfoMain("相机连接已断开（设备已关闭）");
            return true;
            //base.DisConnectDev();
        }

        /// <summary>
        /// 设置曝光时间 在setParameter方法中已有设置曝光时间，另外单独设置，是因为曝光更改可能比较频繁
        /// </summary>
        /// <param name="dValue">曝光值，单位微秒</param>
        /// <returns></returns>
        public override bool setExposureTime(float dValue)
        {
            int nRet;
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return false;
            }

            interMycam.MV_CC_SetEnumValue_NET("ExposureAuto", 0);

            nRet = interMycam.MV_CC_SetFloatValue_NET("ExposureTime", dValue);
            if (nRet != MyCamera.MV_OK)
            {
                //ShowErrorMsg("Set Exposure Time Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 相机设置曝光时间出错");
                displalyInfo.displayInfoMain(findSerialNo+" 相机设置曝光时间出错");
                return false;
            }
            return true;
            //return base.setExposureTime(dValue);//调用基类上已经被重写的对应的方法
        }

        /// <summary>
        /// 设置相机的曝光、增益和帧率
        /// </summary>
        /// <param name="exposure">曝光时间，微秒</param>
        /// <param name="gain">增益值 ，每个相机不同，常规0-20.7</param>
        /// <param name="frame">帧率 每个相机不同</param>
        public override void SetParamter(float exposure, float gain, float frame)
        {
            int nRet;
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return;
            }

            interMycam.MV_CC_SetEnumValue_NET("ExposureAuto", 0);

            nRet = interMycam.MV_CC_SetFloatValue_NET("ExposureTime", exposure);
            if (nRet != MyCamera.MV_OK)
            {
                //ShowErrorMsg("Set Exposure Time Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 相机设置曝光时间");
                displalyInfo.displayInfoMain(findSerialNo+" 相机设置曝光时间出错");
                return;
            }


            interMycam.MV_CC_SetEnumValue_NET("GainAuto", 0);
            nRet =interMycam.MV_CC_SetFloatValue_NET("Gain", gain);
            if (nRet != MyCamera.MV_OK)
            {
                //ShowErrorMsg("Set Gain Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 相机设置增益出错");
                displalyInfo.displayInfoMain(findSerialNo+" 相机设置增益出错");
                return;
            }

            nRet = interMycam.MV_CC_SetFloatValue_NET("AcquisitionFrameRate", frame);
            if (nRet != MyCamera.MV_OK)
            {
                //ShowErrorMsg("Set Frame Rate Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 相机设置帧率出错");
                displalyInfo.displayInfoMain(findSerialNo+" 相机设置帧率出错");
                return;
            }
            //base.SetParamter(exposure, gain, frame);//调用基类上已被其它方法重写的方法
        }

        public override void GetParameter(ref float expoure, ref float gain, ref float frame)
        {
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return;
            }
            MyCamera.MVCC_FLOATVALUE stParam = new MyCamera.MVCC_FLOATVALUE();
            int nRet = interMycam.MV_CC_GetFloatValue_NET("ExposureTime", ref stParam);
            if (MyCamera.MV_OK == nRet)
            {
                expoure = stParam.fCurValue;
                interMycam.MV_CC_GetFloatValue_NET("Gain", ref stParam);
                gain = stParam.fCurValue;
                interMycam.MV_CC_GetFloatValue_NET("ResultingFrameRate", ref stParam);
                frame = stParam.fCurValue;
            }
            else
            {
                //MessageBox.Show(findSerialNo+" 获取相机 曝光、增益、帧率 出错");
                displalyInfo.displayInfoMain(findSerialNo + " 获取相机 曝光、增益、帧率 出错");
            }
        }

        /// <summary>
        /// 设置触发模式
        /// </summary>
        /// <param name="mode">触发模式，可以为连续采集，外触发，软件触发</param>
        /// <returns></returns>
        public override bool SetTriggerMode(TriggerMode mode)
        {
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return false;
            }
            if (mode==TriggerMode.continual)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 0);
                return true;
            }
            else if (mode==TriggerMode.hardTrigger)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 1);
                interMycam.MV_CC_SetEnumValue_NET("TriggerSource", 0);
                return true;
            }
            else if (mode==TriggerMode.softTrigger)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 1);
                interMycam.MV_CC_SetEnumValue_NET("TriggerSource", 7);
                return true;
            }
            else if (mode == TriggerMode.riseEdge)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 1);
                interMycam.MV_CC_SetEnumValue_NET("TriggerSource", 0);
                interMycam.MV_CC_SetEnumValue_NET("TriggerActivation", 0);
                return true;
            }
            else if (mode == TriggerMode.fallEdge)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 1);
                interMycam.MV_CC_SetEnumValue_NET("TriggerSource", 0);
                interMycam.MV_CC_SetEnumValue_NET("TriggerActivation", 1);
                return true;
            }
            else
            {
                //MessageBox.Show(findSerialNo+" 设置触发模式出错");
                displalyInfo.displayInfoMain(findSerialNo+" 设置触发模式出错");
                return false;
            }
            // ch:触发源选择:0 - Line0; | en:Trigger source select:0 - Line0;
            //           1 - Line1;
            //           2 - Line2;
            //           3 - Line3;
            //           4 - Counter;
            //           7 - Software;
        }

        public override bool CaptureImage(bool softTrigger)
        {
            int nRet;
            if (interMycam==null||interMycam.GetCameraHandle()==IntPtr.Zero )
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo+" 相机没有正确打开或相机句柄为空");
                return false;
            }
            MyCamera.MVCC_ENUMVALUE enumPara = new MyCamera.MVCC_ENUMVALUE();
            nRet = interMycam.MV_CC_GetEnumValue_NET("TriggerMode", ref enumPara);
            if (MyCamera.MV_OK != nRet)
            {
                //ShowErrorMsg("Trigger Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 软触发时，获取触发模式出错");
                displalyInfo.displayInfoMain(findSerialNo+" 软触发时，获取触发模式出错");
                return false;
            }
            if (enumPara.nCurValue!=1)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerMode", 1);
            }
            interMycam.MV_CC_GetEnumValue_NET("TriggerSource", ref enumPara);
            if (MyCamera.MV_OK != nRet)
            {
                //ShowErrorMsg("Trigger Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 软触发时，获取触发源出错");
                displalyInfo.displayInfoMain(findSerialNo+" 软触发，获取触发源出错");
                return false;
            }
            if (enumPara.nCurValue!= 7)
            {
                interMycam.MV_CC_SetEnumValue_NET("TriggerSource", 7);
            }
            // ch:触发命令 | en:Trigger command
            nRet = interMycam.MV_CC_SetCommandValue_NET("TriggerSoftware");
            if (MyCamera.MV_OK != nRet)
            {
                //ShowErrorMsg("Trigger Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 软触发时，设置软触发模式出错");
                displalyInfo.displayInfoMain(findSerialNo+" 软触发，设置触发模式出错");
                return false;
            }
            return true;
            //return base.CaptureImage(softTrigger);
        }
        public bool softTrigger()
        {
            softSW.Restart();
            int nRet;
            if (interMycam == null || interMycam.GetCameraHandle() == IntPtr.Zero)
            {
                //MessageBox.Show(findSerialNo+" 相机没有正确打开或相机句柄为空");
                displalyInfo.displayInfoMain(findSerialNo + " 相机没有正确打开或相机句柄为空");
                return false;
            }
            nRet = interMycam.MV_CC_SetCommandValue_NET("TriggerSoftware");
            if (MyCamera.MV_OK != nRet)
            {
                //ShowErrorMsg("Trigger Fail!", nRet);
                //MessageBox.Show(findSerialNo+" 软触发时，设置软触发模式出错");
                displalyInfo.displayInfoMain(findSerialNo + " 软触发，设置触发模式出错");
                return false;
            }
            //displalyInfo.displayInfoMain("触发耗时："+softSW.ElapsedMilliseconds.ToString());
            return true;
            //return base.CaptureImage(softTrigger);
        }

    }
}
